package com.zl.ble;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;

import com.zl.ble.client.BluetoothClient;
import com.zl.ble.service.BluetoothService;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class BluetoothManger {
    private static BluetoothManger manger;
    private BluetoothService mBluetoothService;
    private BluetoothClient mBluetoothClient;
    private boolean isService = false;

    public static BluetoothManger getInstance() {
        if (manger == null) {
            synchronized (BluetoothManger.class) {
                if (manger == null) {
                    manger = new BluetoothManger();
                }
            }
        }
        return manger;
    }

    public void setBluetoothType(boolean isService) {
        this.isService = isService;
        if (isService) {
            if (mBluetoothClient != null) {
                mBluetoothClient.cleanConnect();
                mBluetoothClient = null;
            }
            if (mBluetoothService != null) {
                mBluetoothService.reStart();
            } else {
                mBluetoothService = new BluetoothService();
            }
        } else {
            if (mBluetoothService != null) {
                mBluetoothService.stop();
                mBluetoothService = null;
            }
            if (mBluetoothClient != null) {
                mBluetoothClient.cleanConnect();
            } else {
                mBluetoothClient = new BluetoothClient();
            }
        }
    }

    public void connectService(String addressMac) {
        if (isService || null == mBluetoothClient) {
            return;
        }
        if (!BluetoothAdapter.checkBluetoothAddress(addressMac)) {
            throw new IllegalArgumentException("mac address is not correct! make sure it's upper case!");
        }
        mBluetoothClient.connect(addressMac);
    }

    public void reStart() {
        if (isService && mBluetoothService != null) {
            mBluetoothService.reStart();
        }
        if (!isService && mBluetoothClient != null) {
            mBluetoothClient.cleanConnect();
        }
    }

    public void onDestroy() {
        if (mBluetoothService != null) {
            mBluetoothService.stop();
            mBluetoothService = null;
        }
        if (mBluetoothClient != null) {
            mBluetoothClient.cleanConnect();
            mBluetoothClient = null;
        }
    }

    public void sendMessage(byte[] msg) {
        if (isService && mBluetoothService != null) {
            mBluetoothService.write(msg);
        }
        if (!isService && mBluetoothClient != null) {
            mBluetoothClient.write(msg);
        }
    }


    public void setReceiveListener(ReceiveListener mReceiveListener) {
        if (isService && mBluetoothService != null) {
            mBluetoothService.setReceiveListener(mReceiveListener);
        }
        if (!isService && mBluetoothClient != null) {
            mBluetoothClient.setReceiveListener(mReceiveListener);
        }
    }

    public int getBluetoothStatus() {
        if (isService && mBluetoothService != null) {
            return mBluetoothService.getState();
        }
        if (!isService && mBluetoothClient != null) {
            mBluetoothClient.getState();
        }
        return -1;
    }

    public boolean checkAndOpenBluetooth() {
        if (BluetoothAdapter.getDefaultAdapter() == null) {
            return false;
        }
        if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
            return BluetoothAdapter.getDefaultAdapter().enable();
        }
        return true;
    }

    /**
     * 设置蓝牙设备可被检测
     * 默认120秒可见
     * 0-表示始终可见
     *
     * @param seconds [0-3600]
     */
    public void setDiscoverable(Context mContext, int seconds) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, seconds);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    /**
     * 搜索本地已经配对的设备
     * test pass
     */
    public List<BluetoothDevice> searchLocalDevice() {
        Set<BluetoothDevice> devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
        List<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
        for (BluetoothDevice deivce : devices) {
            list.add(deivce);
        }
        return list;
    }

    /**
     * 搜索未知设备
     * test pass
     */
    public boolean searchUnkonwnDevices() {
        return BluetoothAdapter.getDefaultAdapter().startDiscovery();
    }


    public static String getBluetoothMacAddress() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        String bluetoothMacAddress = "";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            try {
                Field mServiceField = bluetoothAdapter.getClass().getDeclaredField("mService");
                mServiceField.setAccessible(true);
                Object btManagerService = mServiceField.get(bluetoothAdapter);
                if (btManagerService != null) {
                    bluetoothMacAddress = (String) btManagerService.getClass().getMethod("getAddress").invoke(btManagerService);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            bluetoothMacAddress = bluetoothAdapter.getAddress();
        }
        return bluetoothMacAddress;
    }
}
